import asyncio
import string
import threading

import aiofiles
from PIL import Image, ImageDraw, ImageFont
from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.types import (
    KeyboardButton,
    ReplyKeyboardMarkup,
)

import client
import client_kb
import sqlite_db
from common_utils import paste_watermark
from create_bot import bot
from .mx_country_menu import create_mx


class FSM(StatesGroup):
    create_mx_bill = State()

    create_mx_bill_family = State()
    create_mx_bill_name = State()
    create_mx_bill_flate_number = State()
    create_mx_bill_street = State()
    create_mx_bill_city = State()
    create_mx_bill_postcode = State()

    change_mx_bill = State()
    change_mx_bill_what = State()
    change_mx_bill_family = State()
    change_mx_bill_name = State()
    change_mx_bill_flate_number = State()
    change_mx_bill_street = State()
    change_mx_bill_city = State()
    change_mx_bill_postcode = State()
    change_mx_bill_go = State()


# async def command_create_mx(message: types.Message):
#     user_id = message.from_user.id
#     await sqlite_db.sql_check_user(user_id)
#     await bot.send_message(user_id, 'Выберите документ для создания',
#                            reply_markup=client_kb.kb_mx)
#     await FSM.create_mx_bill.set()


async def command_create_mx_bill(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    country = "mx_bill"
    await sqlite_db.sql_add_country_user(user_id, country)
    messagetoedit = await bot.send_message(
        user_id,
        f"Данные клиента\n"
        f"Фамилия:\n"
        f"Имя:\n"
        f"Номер дома:\n"
        f"Улица:\n"
        f"Город:\n"
        f"Посткод:",
        reply_markup=client_kb.cancelledKeyboard,
    )
    msg_delete = await bot.send_message(user_id, "Введите фамилию ✏️")
    async with state.proxy() as data:
        data["message_edit"] = messagetoedit["message_id"]
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.create_mx_bill_family.set()


async def command_create_mx_bill_family(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["family"] = message.text
    if message.text == "Назад ◀️":
        await create_mx(message)
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f"Имя:\n"
            f"Номер дома:\n"
            f"Улица:\n"
            f"Город:\n"
            f"Посткод:",
        )
        msg_delete = await bot.send_message(
            user_id, "Введите имя ✏️", reply_markup=client_kb.cancelledKeyboard
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_mx_bill_name.set()


async def command_create_mx_bill_name(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["name"] = message.text

    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f"Фамилия:\n"
            f"Имя:\n"
            f"Номер дома:\n"
            f"Улица:\n"
            f"Город:\n"
            f"Посткод:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(user_id, "Введите фамилию ✏️")
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_mx_bill_family.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f"Номер дома:\n"
            f"Улица:\n"
            f"Город:\n"
            f"Посткод:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите номер дома ✏️\n" 'либо нажмите "Пропустить"',
            reply_markup=ReplyKeyboardMarkup(
                resize_keyboard=True, one_time_keyboard=True
            )
            .add(KeyboardButton("Пропустить"))
            .add(KeyboardButton("Назад ◀️")),
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_mx_bill_flate_number.set()


async def command_create_mx_bill_flate_number(
    message: types.Message, state: FSMContext
):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["flate_number"] = message.text

    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f"Имя:\n"
            f"Номер дома:\n"
            f"Улица:\n"
            f"Город:\n"
            f"Посткод:",
        )
        msg_delete = await bot.send_message(
            user_id, "Введите имя ✏️", reply_markup=client_kb.cancelledKeyboard
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_mx_bill_name.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f'✅ Номер дома: {data["flate_number"]}\n'
            f"Улица:\n"
            f"Город:\n"
            f"Посткод:",
            reply_markup=client_kb.kb_delete,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите название улицы ✏️",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_mx_bill_street.set()


async def command_create_mx_bill_street(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["street"] = message.text

    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f"Номер дома:\n"
            f"Улица:\n"
            f"Город:\n"
            f"Посткод:",
            reply_markup=client_kb.kb_delete,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите номер дома ✏️\n" 'либо нажмите "Пропустить"',
            reply_markup=ReplyKeyboardMarkup(
                resize_keyboard=True, one_time_keyboard=True
            )
            .add(KeyboardButton("Пропустить"))
            .add(KeyboardButton("Назад ◀️")),
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_mx_bill_flate_number.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f'✅ Номер дома: {data["flate_number"]}\n'
            f'✅ Улица: {data["street"]}\n'
            f"Город:\n"
            f"Посткод:",
            reply_markup=client_kb.kb_delete,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите название города ✏️",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_mx_bill_city.set()


async def command_create_mx_bill_city(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["city"] = message.text
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f'✅ Номер дома: {data["flate_number"]}\n'
            f"Улица:\n"
            f"Город:\n"
            f"Посткод:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите название улицы ✏️",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_mx_bill_street.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f'✅ Номер дома: {data["flate_number"]}\n'
            f'✅ Улица: {data["street"]}\n'
            f'✅ Город: {data["city"]}\n'
            f"Посткод:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id, "Введите посткод ✏️", reply_markup=client_kb.cancelledKeyboard
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_mx_bill_postcode.set()


async def command_create_mx_bill_postcode(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    async with state.proxy() as data:
        data["postcode"] = message.text
    if message.text == "Назад ◀️":
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f'✅ Номер дома: {data["flate_number"]}\n'
            f'✅ Улица: {data["street"]}\n'
            f"Город:\n"
            f"Посткод:",
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id,
            "Введите название города ✏️",
            reply_markup=client_kb.cancelledKeyboard,
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
        await FSM.create_mx_bill_city.set()
    else:
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=message.message_id
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["msg_delete"]
            )
        except:
            pass
        try:
            await bot.delete_message(
                chat_id=message.from_user.id, message_id=data["message_edit"]
            )
        except:
            pass
        messagetoedit = await bot.send_message(
            user_id,
            f"Данные клиента\n"
            f'✅ Фамилия: {data["family"]}\n'
            f'✅ Имя: {data["name"]}\n'
            f'✅ Номер дома: {data["flate_number"]}\n'
            f'✅ Улица: {data["street"]}\n'
            f'✅ Город: {data["city"]}\n'
            f'✅ Посткод: {data["postcode"]}',
            reply_markup=client_kb.cancelledKeyboard,
        )
        msg_delete = await bot.send_message(
            user_id, "Ожидайте генерируется...", reply_markup=client_kb.kb_delete
        )
        async with state.proxy() as data:
            data["message_edit"] = messagetoedit["message_id"]
            data["msg_delete"] = msg_delete["message_id"]
            try:
                thr = threading.Thread(
                    target=process_generate_bill,
                    args=(user_id, data),
                    name=f"thr-{user_id}",
                )
                thr.start()
                while thr.is_alive():
                    await asyncio.sleep(1)
                async with aiofiles.open(
                    f"./files/mx_bill/photo_usr/{user_id}_wm.png", "rb"
                ) as f:
                    await bot.send_document(chat_id=user_id, document=f)
                await bot.send_message(
                    user_id,
                    "Завершите покупку документа.",
                    reply_markup=client_kb.kb_mx_finish_bill,
                )
                try:
                    await bot.delete_message(
                        chat_id=user_id, message_id=data["msg_delete"]
                    )
                except:
                    pass
                await FSM.change_mx_bill.set()
            except Exception as ex:
                print("Ошибка в генерации mx bill:", ex)
                async with state.proxy() as data:
                    try:
                        await bot.delete_message(
                            chat_id=message.from_user.id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    msg_delete = await bot.send_message(
                        user_id,
                        "Ошибка при генерации, проверьте введенные данные",
                        reply_markup=client_kb.kb_uk_change_error,
                    )
                    data["message_edit"] = messagetoedit["message_id"]
                    data["msg_delete"] = msg_delete["message_id"]
                    await FSM.change_mx_bill.set()


import datetime
import locale
import random
import textwrap

import dateutil.relativedelta


def process_generate_bill(user_id, data):
    # try:
    bill = Image.open(f"./files/mx_bill/bill_mexico.png").convert("RGBA")
    txt = Image.new("RGBA", bill.size, (255, 255, 255, 0))
    fnt_semibold = ImageFont.truetype(
        f"./files/mx_bill/ofont.ru_Helvetica Neue.ttf", size=24
    )
    fnt_regular = ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=20)
    fnt_regular_bold = ImageFont.truetype(
        f"./files/mx_bill/ofont.ru_Arial.ttf", size=18
    )
    fnt_regular_italic = ImageFont.truetype(
        f"./files/mx_bill/Arial Italic.ttf", size=19
    )

    go_txt = ImageDraw.Draw(txt)

    fio = str(data["name"]) + " " + str(data["family"])
    go_txt.text(xy=(67, 195), text=f"{fio.upper()}", font=fnt_semibold, fill="#000000")

    if data["flate_number"] == "Пропустить":
        if len(str(data["street"])) >= 47:
            wrapString = textwrap.wrap(data["street"].title(), width=47)
            go_txt.text(
                xy=(67, 221), text=f"{wrapString[0]}", font=fnt_semibold, fill="#000000"
            )
            go_txt.text(
                xy=(67, 241), text=f"{wrapString[1]}", font=fnt_semibold, fill="#000000"
            )
            go_txt.text(
                xy=(67, 266),
                text=f"{str(data['postcode'].title())}",
                font=fnt_semibold,
                fill="#000000",
            )
            go_txt.text(
                xy=(67, 290),
                text=f"{data['city'].title()}",
                font=fnt_semibold,
                fill="#000000",
            )
        else:
            go_txt.text(
                xy=(67, 221),
                text=f"{(str(data['street'])).title()}",
                font=fnt_semibold,
                fill="#000000",
            )
            go_txt.text(
                xy=(67, 246),
                text=f"{str(data['postcode'].title())}",
                font=fnt_semibold,
                fill="#000000",
            )
            go_txt.text(
                xy=(67, 270),
                text=f"{data['city'].title()}",
                font=fnt_semibold,
                fill="#000000",
            )

    else:
        if len((str(data["flate_number"]) + " " + str(data["street"].title()))) >= 47:
            wrapString = textwrap.wrap(data["street"].title(), width=47)
            go_txt.text(
                xy=(67, 221), text=f"{wrapString[0]}", font=fnt_semibold, fill="#000000"
            )
            try:
                go_txt.text(
                    xy=(67, 241),
                    text=f"{wrapString[1]}",
                    font=fnt_semibold,
                    fill="#000000",
                )
            except:
                pass
            go_txt.text(
                xy=(67, 266),
                text=f"{str(data['postcode'].title())}",
                font=fnt_semibold,
                fill="#000000",
            )
            go_txt.text(
                xy=(67, 290),
                text=f"{data['city'].title()}",
                font=fnt_semibold,
                fill="#000000",
            )
        else:
            go_txt.text(
                xy=(67, 221),
                text=f"{(str(data['flate_number']) + ' ' + str(data['street'].title()))}",
                font=fnt_semibold,
                fill="#000000",
            )
            go_txt.text(
                xy=(67, 246),
                text=f"{str(data['postcode'].title())}",
                font=fnt_semibold,
                fill="#000000",
            )
            go_txt.text(
                xy=(67, 270),
                text=f"{data['city'].title()}",
                font=fnt_semibold,
                fill="#000000",
            )

    # randomUnic
    locale.setlocale(locale.LC_ALL, "es_MX")

    cuenta = f"06DW06B0100{random.randrange(10000,99999)}"
    go_txt.text(xy=(72, 398), text=f"{cuenta}", font=fnt_regular, fill="#000000")
    go_txt.text(
        xy=(148, 1612),
        text=f"{cuenta}",
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=22),
        fill="#000000",
    )
    randNum = (
        f"{random.randrange(11,99)}{random.choice(string.ascii_letters)}{random.randrange(11,99)}{random.choice(string.ascii_letters)}"
    ).upper()
    go_txt.text(
        xy=(63, 545),
        text=f"{randNum}",
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=21),
        fill="#000000",
    )
    go_txt.text(
        xy=(205, 545),
        text=f"17{random.randrange(100,999)}",
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=21),
        fill="#000000",
    )
    go_txt.text(
        xy=(330, 545),
        text=f"17{random.randrange(100, 999)}",
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=21),
        fill="#000000",
    )
    go_txt.text(
        xy=(610, 545),
        text=f"{random.randrange(530, 540)}",
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=21),
        fill="#000000",
    )
    go_txt.text(
        xy=(80, 1200),
        text=f"{(datetime.datetime.today()).strftime('%Y')}",
        font=fnt_regular_bold,
        fill="#000000",
    )

    nowTime = datetime.datetime.now()
    lastDatetime = nowTime + dateutil.relativedelta.relativedelta(months=2)
    go_txt.text(
        xy=(297, 1466),
        text=f"0{random.randrange(5,7)} {(nowTime.strftime('%B')).upper()[0:3]} {(datetime.datetime.today()).strftime('%Y')} ",
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=13),
        fill="#000000",
    )

    go_txt.text(
        xy=(782, 233),
        text=f"387 {random.randrange(100,999)} {random.randrange(100,999)} {random.randrange(100,999)}",
        font=ImageFont.truetype(
            f"./files/mx_bill/ofont.ru_Helvetica Neue.ttf", size=40
        ),
        fill="#000000",
    )
    go_txt.text(
        xy=(835, 312),
        text=f"17 {((datetime.datetime.now() - dateutil.relativedelta.relativedelta(months=1)).strftime('%B'))[0:3]} {(datetime.datetime.today()).strftime('%Y')[2:4]}".upper(),
        font=ImageFont.truetype(
            f"./files/mx_bill/ofont.ru_Helvetica Neue.ttf", size=40
        ),
        fill="#000000",
    )
    go_txt.text(
        xy=(873, 429),
        text=f"18 {((datetime.datetime.now() - dateutil.relativedelta.relativedelta(months=1)).strftime('%B'))[0:3]} {(datetime.datetime.today()).strftime('%Y')[2:4]}".upper(),
        font=fnt_regular_italic,
        fill="#000000",
    )

    beforePeriodFirst = datetime.datetime.now() - dateutil.relativedelta.relativedelta(
        months=2
    )
    beforePeriodSecond = datetime.datetime.now() - dateutil.relativedelta.relativedelta(
        months=1
    )
    print(beforePeriodSecond, beforePeriodFirst)
    go_txt.text(
        xy=(719, 600),
        text=f"01 {beforePeriodFirst.strftime('%B')[0:3]} {(datetime.datetime.now()).strftime('%Y')[2:4]}\n      al\n02 {beforePeriodSecond.strftime('%B')[0:3]} {(datetime.datetime.now()).strftime('%Y')[2:4]}".upper(),
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=21),
        fill="#000000",
    )

    go_txt.text(
        xy=(948, 608),
        text=f"{random.randrange(8,10)}.{random.randrange(10,99)}",
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=24),
        fill="#000000",
    )
    go_txt.text(
        xy=(1054, 611),
        text=f"{random.randrange(15, 16)}.{random.randrange(10, 99)}",
        font=ImageFont.truetype(
            f"./files/mx_bill/ofont.ru_Helvetica Neue.ttf", size=30
        ),
        fill="#000000",
    )
    go_txt.text(
        xy=(860, 608),
        text=f"{(datetime.date(2023, beforePeriodSecond.month, 2) - datetime.date(2023, beforePeriodFirst.month, 1)).days}".upper(),
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=24),
        fill="#000000",
    )
    # 1

    basico = random.randrange(150, 160)
    intermedio = random.randrange(200, 210)
    excedente = random.randrange(180, 190)
    suma = int(basico + intermedio + excedente)

    basicoSubtotal = basico * 0.793
    intermedioSubtotal = intermedio * 0.956
    excedenteSubtotal = excedente * 2.802
    sumaSubtotal = basicoSubtotal + intermedioSubtotal + excedenteSubtotal

    go_txt.text(
        xy=(890, 784),
        text=f"{basico}"[0:5],
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=17),
        fill="#000000",
    )
    go_txt.text(
        xy=(1088, 784),
        text=f"{basicoSubtotal}"[0:5],
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=17),
        fill="#000000",
    )

    go_txt.text(
        xy=(890, 808),
        text=f"{intermedio}"[0:5],
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=17),
        fill="#000000",
    )
    go_txt.text(
        xy=(1088, 808),
        text=f"{intermedioSubtotal}"[0:5],
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=17),
        fill="#000000",
    )

    go_txt.text(
        xy=(890, 831),
        text=f"{excedente}"[0:5],
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=17),
        fill="#000000",
    )
    go_txt.text(
        xy=(1088, 831),
        text=f"{excedenteSubtotal}"[0:5],
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=17),
        fill="#000000",
    )

    go_txt.text(
        xy=(890, 854),
        text=f"{suma}"[0:5],
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=17),
        fill="#000000",
    )
    go_txt.text(
        xy=(1088, 854),
        text=f"{sumaSubtotal}"[0:5],
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=17),
        fill="#000000",
    )

    energiaIva = sumaSubtotal / 100 * 16
    Fac = sumaSubtotal + energiaIva

    go_txt.text(
        xy=(1070, 1146),
        text=f"{sumaSubtotal}"[0:6],
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=17),
        fill="#000000",
    )
    go_txt.text(
        xy=(1070, 1169),
        text=f"{energiaIva}"[0:6],
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=17),
        fill="#000000",
    )
    go_txt.text(
        xy=(1070, 1192),
        text=f"{Fac}"[0:6],
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=17),
        fill="#000000",
    )
    go_txt.text(
        xy=(1070, 1215),
        text=f"{random.randrange(97,99)}{random.randrange(1,9)}.{random.randrange(10,99)}"[
            0:5
        ],
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=17),
        fill="#000000",
    )
    go_txt.text(
        xy=(1070, 1239),
        text=f"{random.randrange(97, 99)}{random.randrange(1, 9)}.{random.randrange(10, 99)}"[
            0:6
        ],
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=17),
        fill="#000000",
    )
    go_txt.text(
        xy=(1070, 1261),
        text=f"{Fac}"[0:5],
        font=ImageFont.truetype(f"./files/mx_bill/ArialRegular.ttf", size=17),
        fill="#000000",
    )

    go_txt.text(
        xy=(888, 1535),
        text=f"${Fac}"[0:6],
        font=ImageFont.truetype(
            f"./files/mx_bill/ofont.ru_Helvetica Neue.ttf", size=45
        ),
        fill="#000000",
    )
    go_txt.text(
        xy=(860, 110),
        text=f"${Fac}"[0:6],
        font=ImageFont.truetype(
            f"./files/mx_bill/ofont.ru_Helvetica Neue.ttf", size=48
        ),
        fill="#000000",
    )

    result = Image.alpha_composite(bill, txt)
    result.save(f"./files/mx_bill/photo_usr/{user_id}_completed.png")

    paste_watermark(
        f"./files/mx_bill/photo_usr/{user_id}_completed.png",
        f"./files/mx_bill/photo_usr/{user_id}_wm.png",
    )

    print("gotovo")
    # except Exception as ex:
    #     print('ошибка process_uk_bill: ', ex)
    #     try:
    #         os.remove(f'./files/mx_bill/{user_id}.png')
    #     except:
    #         pass
    #     try:
    #         os.remove(f'./files/mx_bill/photo_usr/{user_id}_completed.png')
    #     except:
    #         pass
    #     try:
    #         os.remove(f'./files/mx_bill/photo_usr/{user_id}_wm.png')
    #     except:
    #         pass
    #     return


# todo: CHANHE
async def command_change_mx_bill(callback: types.CallbackQuery, state: FSMContext):
    user_id = callback.from_user.id
    try:
        await bot.delete_message(
            chat_id=callback.from_user.id, message_id=callback.message.message_id
        )
    except:
        pass
    msg_delete = await bot.send_message(
        user_id,
        "Выберите параметр, который хотите изменить",
        reply_markup=client_kb.kb_mx_change_go_bill,
    )
    async with state.proxy() as data:
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_mx_bill_what.set()


async def command_change_mx_bill_family(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id, "Введите фамилию ✏️", reply_markup=client_kb.kb_delete
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "family"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_mx_bill_go.set()


async def command_change_mx_bill_name(callback: types.CallbackQuery, state: FSMContext):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id, "Введите имя ✏️", reply_markup=client_kb.kb_delete
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "name"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_mx_bill_go.set()


async def command_change_mx_bill_flate_number(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id,
        "Введите номер дома ✏️\n" 'либо нажмите "Пропустить"',
        reply_markup=client_kb.kb_skip,
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "flate_number"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_mx_bill_go.set()


async def command_change_mx_bill_street(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id, "Введите название улицы ✏️", reply_markup=client_kb.kb_delete
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "street"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_mx_bill_go.set()


async def command_change_mx_bill_city(callback: types.CallbackQuery, state: FSMContext):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id, "Введите название города ✏️", reply_markup=client_kb.kb_delete
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "city"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_mx_bill_go.set()


async def command_change_mx_bill_postcode(
    callback: types.CallbackQuery, state: FSMContext
):
    user_id = callback.from_user.id
    msg_delete = await bot.send_message(
        user_id, "Введите посткод ✏️", reply_markup=client_kb.kb_delete
    )
    async with state.proxy() as data:
        try:
            await bot.delete_message(chat_id=user_id, message_id=data["msg_delete"])
        except:
            pass
        data["what_change"] = "postcode"
        data["msg_delete"] = msg_delete["message_id"]
    await FSM.change_mx_bill_go.set()


async def command_change_mx_bill_go(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    msg = message.text
    try:
        await bot.delete_message(
            chat_id=message.from_user.id, message_id=message.message_id
        )
    except:
        pass
    async with state.proxy() as data:
        if data["what_change"] == "family":
            async with state.proxy() as data:
                data["family"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            messagetoedit = await bot.send_message(
                user_id,
                f"Данные клиента\n"
                f'✅ Фамилия: {data["family"]}\n'
                f'✅ Имя: {data["name"]}\n'
                f'✅ Номер дома: {data["flate_number"]}\n'
                f'✅ Улица: {data["street"]}\n'
                f'✅ Город: {data["city"]}\n'
                f'✅ Посткод: {data["postcode"]}',
            )
            msg_delete = await bot.send_message(
                user_id, "Ожидайте генерируется...", reply_markup=client_kb.kb_delete
            )
            async with state.proxy() as data:
                data["message_edit"] = messagetoedit["message_id"]
                data["msg_delete"] = msg_delete["message_id"]
                try:
                    thr = threading.Thread(
                        target=process_generate_bill,
                        args=(user_id, data),
                        name=f"thr-{user_id}",
                    )
                    thr.start()
                    while thr.is_alive():
                        await asyncio.sleep(1)
                    async with aiofiles.open(
                        f"./files/mx_bill/photo_usr/{user_id}_wm.png", "rb"
                    ) as f:
                        await bot.send_document(chat_id=user_id, document=f)
                    await bot.send_message(
                        user_id,
                        "Завершите покупку документа.",
                        reply_markup=client_kb.kb_mx_finish_bill,
                    )
                    try:
                        await bot.delete_message(
                            chat_id=user_id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    await FSM.change_mx_bill.set()
                except Exception as ex:
                    print("Ошибка в генерации mx bill:", ex)
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "Ошибка при генерации, проверьте введенные данные",
                            reply_markup=client_kb.kb_mx_change_error,
                        )
                        data["message_edit"] = messagetoedit["message_id"]
                        data["msg_delete"] = msg_delete["message_id"]
                        await FSM.change_mx_bill.set()
        elif data["what_change"] == "name":
            async with state.proxy() as data:
                data["name"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            messagetoedit = await bot.send_message(
                user_id,
                f"Данные клиента\n"
                f'✅ Фамилия: {data["family"]}\n'
                f'✅ Имя: {data["name"]}\n'
                f'✅ Номер дома: {data["flate_number"]}\n'
                f'✅ Улица: {data["street"]}\n'
                f'✅ Город: {data["city"]}\n'
                f'✅ Посткод: {data["postcode"]}',
            )
            msg_delete = await bot.send_message(
                user_id, "Ожидайте генерируется...", reply_markup=client_kb.kb_delete
            )
            async with state.proxy() as data:
                data["message_edit"] = messagetoedit["message_id"]
                data["msg_delete"] = msg_delete["message_id"]
                try:
                    thr = threading.Thread(
                        target=process_generate_bill,
                        args=(user_id, data),
                        name=f"thr-{user_id}",
                    )
                    thr.start()
                    while thr.is_alive():
                        await asyncio.sleep(1)
                    async with aiofiles.open(
                        f"./files/mx_bill/photo_usr/{user_id}_wm.png", "rb"
                    ) as f:
                        await bot.send_document(chat_id=user_id, document=f)
                    await bot.send_message(
                        user_id,
                        "Завершите покупку документа.",
                        reply_markup=client_kb.kb_mx_finish_bill,
                    )
                    try:
                        await bot.delete_message(
                            chat_id=user_id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    await FSM.change_mx_bill.set()
                except Exception as ex:
                    print("Ошибка в генерации mx bill:", ex)
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "Ошибка при генерации, проверьте введенные данные",
                            reply_markup=client_kb.kb_mx_change_error,
                        )
                        data["message_edit"] = messagetoedit["message_id"]
                        data["msg_delete"] = msg_delete["message_id"]
                        await FSM.change_mx_bill.set()
        elif data["what_change"] == "flate_number":
            async with state.proxy() as data:
                data["flate_number"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            messagetoedit = await bot.send_message(
                user_id,
                f"Данные клиента\n"
                f'✅ Фамилия: {data["family"]}\n'
                f'✅ Имя: {data["name"]}\n'
                f'✅ Номер дома: {data["flate_number"]}\n'
                f'✅ Улица: {data["street"]}\n'
                f'✅ Город: {data["city"]}\n'
                f'✅ Посткод: {data["postcode"]}',
            )
            msg_delete = await bot.send_message(
                user_id, "Ожидайте генерируется...", reply_markup=client_kb.kb_delete
            )
            async with state.proxy() as data:
                data["message_edit"] = messagetoedit["message_id"]
                data["msg_delete"] = msg_delete["message_id"]
                try:
                    thr = threading.Thread(
                        target=process_generate_bill,
                        args=(user_id, data),
                        name=f"thr-{user_id}",
                    )
                    thr.start()
                    while thr.is_alive():
                        await asyncio.sleep(1)
                    async with aiofiles.open(
                        f"./files/mx_bill/photo_usr/{user_id}_wm.png", "rb"
                    ) as f:
                        await bot.send_document(chat_id=user_id, document=f)
                    await bot.send_message(
                        user_id,
                        "Завершите покупку документа.",
                        reply_markup=client_kb.kb_mx_finish_bill,
                    )
                    try:
                        await bot.delete_message(
                            chat_id=user_id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    await FSM.change_mx_bill.set()
                except Exception as ex:
                    print("Ошибка в генерации mx bill:", ex)
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "Ошибка при генерации, проверьте введенные данные",
                            reply_markup=client_kb.kb_mx_change_error,
                        )
                        data["message_edit"] = messagetoedit["message_id"]
                        data["msg_delete"] = msg_delete["message_id"]
                        await FSM.change_mx_bill.set()
        elif data["what_change"] == "street":
            async with state.proxy() as data:
                data["street"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            messagetoedit = await bot.send_message(
                user_id,
                f"Данные клиента\n"
                f'✅ Фамилия: {data["family"]}\n'
                f'✅ Имя: {data["name"]}\n'
                f'✅ Номер дома: {data["flate_number"]}\n'
                f'✅ Улица: {data["street"]}\n'
                f'✅ Город: {data["city"]}\n'
                f'✅ Посткод: {data["postcode"]}',
            )
            msg_delete = await bot.send_message(
                user_id, "Ожидайте генерируется...", reply_markup=client_kb.kb_delete
            )
            async with state.proxy() as data:
                data["message_edit"] = messagetoedit["message_id"]
                data["msg_delete"] = msg_delete["message_id"]
                try:
                    thr = threading.Thread(
                        target=process_generate_bill,
                        args=(user_id, data),
                        name=f"thr-{user_id}",
                    )
                    thr.start()
                    while thr.is_alive():
                        await asyncio.sleep(1)
                    async with aiofiles.open(
                        f"./files/mx_bill/photo_usr/{user_id}_wm.png", "rb"
                    ) as f:
                        await bot.send_document(chat_id=user_id, document=f)
                    await bot.send_message(
                        user_id,
                        "Завершите покупку документа.",
                        reply_markup=client_kb.kb_mx_finish_bill,
                    )
                    try:
                        await bot.delete_message(
                            chat_id=user_id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    await FSM.change_mx_bill.set()
                except Exception as ex:
                    print("Ошибка в генерации mx bill:", ex)
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "Ошибка при генерации, проверьте введенные данные",
                            reply_markup=client_kb.kb_mx_change_error,
                        )
                        data["message_edit"] = messagetoedit["message_id"]
                        data["msg_delete"] = msg_delete["message_id"]
                        await FSM.change_mx_bill.set()
        elif data["what_change"] == "city":
            async with state.proxy() as data:
                data["city"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            messagetoedit = await bot.send_message(
                user_id,
                f"Данные клиента\n"
                f'✅ Фамилия: {data["family"]}\n'
                f'✅ Имя: {data["name"]}\n'
                f'✅ Номер дома: {data["flate_number"]}\n'
                f'✅ Улица: {data["street"]}\n'
                f'✅ Город: {data["city"]}\n'
                f'✅ Посткод: {data["postcode"]}',
            )
            msg_delete = await bot.send_message(
                user_id, "Ожидайте генерируется...", reply_markup=client_kb.kb_delete
            )
            async with state.proxy() as data:
                data["message_edit"] = messagetoedit["message_id"]
                data["msg_delete"] = msg_delete["message_id"]
                try:
                    thr = threading.Thread(
                        target=process_generate_bill,
                        args=(user_id, data),
                        name=f"thr-{user_id}",
                    )
                    thr.start()
                    while thr.is_alive():
                        await asyncio.sleep(1)
                    async with aiofiles.open(
                        f"./files/mx_bill/photo_usr/{user_id}_wm.png", "rb"
                    ) as f:
                        await bot.send_document(chat_id=user_id, document=f)
                    await bot.send_message(
                        user_id,
                        "Завершите покупку документа.",
                        reply_markup=client_kb.kb_mx_finish_bill,
                    )
                    try:
                        await bot.delete_message(
                            chat_id=user_id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    await FSM.change_mx_bill.set()
                except Exception as ex:
                    print("Ошибка в генерации mx bill:", ex)
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "Ошибка при генерации, проверьте введенные данные",
                            reply_markup=client_kb.kb_mx_change_error,
                        )
                        data["message_edit"] = messagetoedit["message_id"]
                        data["msg_delete"] = msg_delete["message_id"]
                        await FSM.change_mx_bill.set()
        elif data["what_change"] == "postcode":
            async with state.proxy() as data:
                data["postcode"] = msg
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=message.message_id
                )
            except:
                pass
            try:
                await bot.delete_message(
                    chat_id=message.from_user.id, message_id=data["msg_delete"]
                )
            except:
                pass
            messagetoedit = await bot.send_message(
                user_id,
                f"Данные клиента\n"
                f'✅ Фамилия: {data["family"]}\n'
                f'✅ Имя: {data["name"]}\n'
                f'✅ Номер дома: {data["flate_number"]}\n'
                f'✅ Улица: {data["street"]}\n'
                f'✅ Город: {data["city"]}\n'
                f'✅ Посткод: {data["postcode"]}',
            )
            msg_delete = await bot.send_message(
                user_id, "Ожидайте генерируется...", reply_markup=client_kb.kb_delete
            )
            async with state.proxy() as data:
                data["message_edit"] = messagetoedit["message_id"]
                data["msg_delete"] = msg_delete["message_id"]
                try:
                    thr = threading.Thread(
                        target=process_generate_bill,
                        args=(user_id, data),
                        name=f"thr-{user_id}",
                    )
                    thr.start()
                    while thr.is_alive():
                        await asyncio.sleep(1)
                    async with aiofiles.open(
                        f"./files/mx_bill/photo_usr/{user_id}_wm.png", "rb"
                    ) as f:
                        await bot.send_document(chat_id=user_id, document=f)
                    await bot.send_message(
                        user_id,
                        "Завершите покупку документа.",
                        reply_markup=client_kb.kb_mx_finish_bill,
                    )
                    try:
                        await bot.delete_message(
                            chat_id=user_id, message_id=data["msg_delete"]
                        )
                    except:
                        pass
                    await FSM.change_mx_bill.set()
                except Exception as ex:
                    print("Ошибка в генерации mx bill:", ex)
                    async with state.proxy() as data:
                        try:
                            await bot.delete_message(
                                chat_id=message.from_user.id,
                                message_id=data["msg_delete"],
                            )
                        except:
                            pass
                        msg_delete = await bot.send_message(
                            user_id,
                            "Ошибка при генерации, проверьте введенные данные",
                            reply_markup=client_kb.kb_mx_change_error,
                        )
                        data["message_edit"] = messagetoedit["message_id"]
                        data["msg_delete"] = msg_delete["message_id"]
                        await FSM.change_mx_bill.set()


# todo:BUY


async def command_pay_mx_bill(callback: types.CallbackQuery, state: FSMContext):
    async with state.proxy() as data:
        data["pay_country"] = "mx_bill"
    await client.command_promo_quest(callback, state)
